package windowChat;

import guiservice.client.Application;
import guiservice.client.KeyEventHandler;
import guiservice.client.MouseEventHandler;
import guiservice.common.controls.*;
import guiservice.common.controls.Button;
import guiservice.common.controls.Label;
import guiservice.common.controls.TextArea;
import guiservice.common.controls.Window;
import guiservice.common.controls.handlers.KeyEventArgs;
import guiservice.common.controls.handlers.MouseEventArgs;
import guiservice.common.controls.handlers.MouseEventType;
import lombok.extern.log4j.Log4j;

import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;

@Log4j
public class ChatWindow extends Application {

    private final int x;
    private final int y;
    private Window window;
    private Button clearButton, sendButton, automaticDemo;
    private TextBox msgTextBox;
    private Label idLabel, chatLabel, sendLabel;
    private TextArea chatTextArea;

    private String id;

    public ChatWindow(int x, int y) throws IOException {
        super();
        this.x = x;
        this.y = y;
    }

    public void setPoint(int x, int y) {
        window.setPoint(x, y);
    }

    @Override
    public void run() throws IOException, InterruptedException {
        super.run();
        window = createWindow();
        window.setSize(300, 300);
        window.setPoint(x, y);
        window.setTitle("Chat");
        window.setBackGround(Color.lightGray.getRGB());

        idLabel = createLabel(window);
        idLabel.setSize(180, 20);
        idLabel.setPoint(35, 5);
        idLabel.setBackGround(Color.lightGray.getRGB());

        chatLabel = createLabel(window);
        chatLabel.setSize(180, 20);
        chatLabel.setPoint(35, 35);
        chatLabel.setText("Chat log: ");
        chatLabel.setBackGround(Color.lightGray.getRGB());

        chatTextArea = createTextArea(window);
        chatTextArea.setSize(230, 60);
        chatTextArea.setPoint(35, 60);
        chatTextArea.setText("");
        chatTextArea.setBackGround(Color.white.getRGB());

        sendLabel = createLabel(window);
        sendLabel.setSize(180, 20);
        sendLabel.setPoint(35, 125);
        sendLabel.setText("Send form: ");
        sendLabel.setBackGround(Color.lightGray.getRGB());

        msgTextBox = createTextBox(window);
        msgTextBox.setSize(230, 20);
        msgTextBox.setPoint(35, 150);
        msgTextBox.setText("");
        msgTextBox.setBackGround(Color.white.getRGB());


        idLabel.setText("My text area server id: " + chatTextArea.getId());

        addKeyEventListener(msgTextBox, new KeyEventHandler<TextBox>() {
            @Override
            public void handler(TextBox control, KeyEventArgs args) {
                if (args.isPressed()) {
                    String text = control.getText();
                    log.debug(String.format("id=%d get text=%s", msgTextBox.getId(), text));
                    String symbol = args.getSymbol();
                    if ("Backspace".equals(symbol)) {
                        int length = text.length();
                        if (length > 0) {
                            text = text.substring(0, length - 1);
                        }
                    } else {
                        text = text + args.getSymbol();
                    }
                    log.debug(String.format("id=%d set text=%s", msgTextBox.getId(), text));
                    msgTextBox.setText(text);
                    invalidate();
                }
            }
        });

        clearButton = createButton(window);
        clearButton.setSize(80, 20);
        clearButton.setPoint(50, 185);
        clearButton.setBackGround(Color.red.getRGB());
        clearButton.setText("Clear text");

        addMouseEventListener(clearButton, new MouseEventHandler<Button>() {

            @Override
            public void handler(Button clearButton, MouseEventArgs args) {
                msgTextBox.setText("");
                invalidate();
            }
        });

        sendButton = createButton(window);
        sendButton.setSize(110, 20);
        sendButton.setPoint(140, 185);
        sendButton.setBackGround(Color.green.getRGB());
        sendButton.setText("Send message");

        addMouseEventListener(sendButton, new MouseEventHandler<Button>() {

            @Override
            public void handler(Button control, MouseEventArgs args) {
                if (args.getType() == MouseEventType.Clicked) {
                    String text = msgTextBox.getText();
                    if (text == null) {
                        return;
                    }
                    String[] splitted = text.split(":");
                    if (splitted.length == 2) {
                        long targetId = Long.parseLong(splitted[0]);
                        TextArea textArea = getControl(targetId, TextArea.class);
                        textArea.appendText(splitted[1]);
                        //sendUpdateMessage("AppendText", String.format("Message from %s: %s", id, splitted[1]));

                        invalidate();
                    }
                }
            }
        });

        automaticDemo = createButton(window);
        automaticDemo.setSize(140, 20);
        automaticDemo.setPoint(80, 210);
        automaticDemo.setBackGround(Color.blue.getRGB());
        automaticDemo.setText("Automatic demo");

        addMouseEventListener(automaticDemo, new MouseEventHandler<Button>() {

            private boolean isAutomatic = false;

            private long otherClientId = -1;

            private TextArea textArea;

            private Button button;

            private Window otherWindow;

            private Thread sendThread;

            private Thread getSendThread() {
                return new Thread() {

                    @Override
                    public void run() {
                        while (isAutomatic) {
                            try {
                                textArea.appendText(UUID.randomUUID().toString().substring(0, 7));
                                invalidate();
                                Thread.sleep(1500);
                            } catch (InterruptedException e) {
                                return;
                            }
                        }
                    }
                };
            }

            @Override
            public void handler(Button control, MouseEventArgs args) {
                if (args.getType() == MouseEventType.Clicked) {
                    if (!isAutomatic) {
                        if (sendThread != null) {
                            return;
                        }
                        isAutomatic = true;
                        log.debug(String.format("event handled args=%s", args));
                        long otherClient = getOtherClient();
                        if (otherClient != getId()) {
                            otherClientId = otherClient;
                            textArea = getTextAreas(otherClient).get(0);
                            otherWindow = getWindows(otherClient).get(0);
                            List<Button> buttons = getButtons(otherClient);
                            for (Button b : buttons) {
                                String buttonText = b.getText();
                                String needText = control.getText();
                                if (buttonText.equals(needText)) {
                                    button = b;
                                    log.debug("Need button was found");
                                    break;
                                }
                            }
                            otherWindow.setTitle("Chat (automatic)");
                            if (button != null) {
                                String otherTitle = otherWindow.getTitle();
                                String myTitle = window.getTitle();
                                if (!otherTitle.equals(myTitle)) {
                                    eventHandler(button.getId(), otherClient, new MouseEventArgs(0, 0, MouseEventType.Clicked, 0));
                                }
                            }
                            sendThread = getSendThread();
                            sendThread.start();
                            invalidate();
                        }
                    } else if (otherClientId != -1) {
                        if (sendThread == null) {
                            return;
                        }
                        isAutomatic = false;
                        otherWindow.setTitle("Chat");
                        if (button != null) {
                            String otherTitle = otherWindow.getTitle();
                            String myTitle = window.getTitle();
                            if (!otherTitle.equals(myTitle)) {
                                eventHandler(button.getId(), otherClientId, new MouseEventArgs(0, 0, MouseEventType.Clicked, 0));
                            }
                        }
                        try {
                            if (sendThread != null) {
                                sendThread.join(1500);
                            }
                        } catch (InterruptedException e) {
                            log.error("", e);
                        }
                        sendThread = null;
                        invalidate();
                    }
                }
            }
        });

        invalidate();
    }

    private long getOtherClient() {
        Long[] clients = getClients();
        for (Long id : clients) {
            log.debug("Client with id " + id + " was found.");
        }
        long uid = -1;
        for (long client : clients) {
            if (client != getId()) {
                uid = client;
                break;
            }
        }
        return uid;
    }
}
